package com.alphathink.BitMapUtil;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

/**
 * 单例模式。 生成一个HttpClient对象
 * 
 * @author tiaowu
 *
 */
public class HttpClientSingle {
	public static final int BINARY = 0;
	public static final int TEXT = 1;

	private static HttpClient binaryClient;
	private static HttpClient textClient;

	public static synchronized HttpClient getHttpClient(int category) {
		if (category == BINARY) {
			if (binaryClient == null) {
				HttpParams httpParams = new BasicHttpParams();
				HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
				HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
				HttpProtocolParams.setUseExpectContinue(httpParams, true);
				ConnManagerParams.setTimeout(httpParams, 5000);
				HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
				HttpConnectionParams.setSoTimeout(httpParams, 10000);
				SchemeRegistry registry = new SchemeRegistry();
				registry.register(new Scheme("http", PlainSocketFactory
						.getSocketFactory(), 80));
				ClientConnectionManager ccm = new ThreadSafeClientConnManager(
						httpParams, registry);
				binaryClient = new DefaultHttpClient(ccm, httpParams);
				System.out.println("new binary Client");
			}
			System.out
					.println("HttpClientSingle-->getHttpClient-->return binary Client");
			return binaryClient;
		} else {
			if (textClient == null) {
				HttpParams httpParams = new BasicHttpParams();
				HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
				HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
				HttpProtocolParams.setUseExpectContinue(httpParams, true);
				ConnManagerParams.setTimeout(httpParams, 5000);
				HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
				HttpConnectionParams.setSoTimeout(httpParams, 10000);
				SchemeRegistry registry = new SchemeRegistry();
				registry.register(new Scheme("http", PlainSocketFactory
						.getSocketFactory(), 80));
				ClientConnectionManager ccm = new ThreadSafeClientConnManager(
						httpParams, registry);
				textClient = new DefaultHttpClient(ccm, httpParams);
				System.out.println("new text Client");
			}
			System.out
					.println("HttpClientSingle-->getHttpClient-->return text Client");
			return textClient;
		}
	}
}
